package com.eversec.util.properties;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.TreeMap;

public class PropertiesUtil {

	public static String getValueByKey(String propertiesFile, String key) {
		String res = null;
		try {
			InputStream is = PropertiesUtil.class.getClassLoader().getResourceAsStream(propertiesFile);
			Properties p = new Properties();
			p.load(is);
			is.close();
			res = p.getProperty(key);
		} catch (Exception err) {
			err.printStackTrace();
		}
		return res;
	}

	public static String setValueByKey(String propertiesFile, String key, String value) {
		String res = null;
		try {
			String newFilePath = PropertiesUtil.class.getResource("/").getPath();
			File file = new File(newFilePath);
			file = new File(newFilePath + propertiesFile);
			if (!file.exists())
				file.createNewFile();
			InputStream fis = new FileInputStream(file);
			Properties prop = new Properties();
			prop.load(fis);
			fis.close();

			prop.setProperty(key, value);
			OutputStream fos = new FileOutputStream(file.getPath());
			prop.store(fos, null);
			fos.close();
		} catch (Exception err) {
			err.printStackTrace();
		}

		return res;
	}

	/**
	 * 返回所有属性
	 * 
	 * @param propertiesFile
	 * @return
	 */
	public static Map<String, String> getProperties(String propertiesFile) {
		Map<String, String> map = new TreeMap<String, String>();
		InputStream ism = null;
		
		try {
			ism = PropertiesUtil.class.getResourceAsStream(propertiesFile);
			Properties prop = new Properties();
			prop.load(ism);

			for (Entry<Object, Object> entry : prop.entrySet()) {
				if (!entry.getKey().toString().startsWith("#")) {
					map.put(((String) entry.getKey()).trim(), ((String) entry.getValue()).trim());
				}
			}
			return map;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (ism != null) {
				try {
					ism.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}

}
